package cn.chint.manage.controller;

import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.chint.manage.dao.UserDao;
import cn.chint.manage.service.UserService;
import cn.chint.util.BeanUtil;
import cn.chint.util.HTTPClientUtils;
import cn.chint.util.RequestIp;
import cn.chint.util.UtilDate;

import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.service.EntPayService;
import com.github.binarywang.wxpay.service.WxPayService;

@Controller
public class PushMsgController { 
	@Autowired
	UserService userService;
	@Autowired
	UserDao userDao;

	public Logger log = Logger.getLogger(getClass());

	@RequestMapping(value = "push_msg", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String  push_msg(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response)  {
		try{
			log.info("模板消息推送TEST");

			String appid="wx487b598049f3a162";
			String secret = "7afd7b083512837aad16295d2de49b22";
			/**获取TOKEN信息*/
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
			log.info("token请求地址: "+ url);
			String res_json = HTTPClientUtils.getRequest(url);
			log.info("返回token信息: "+ res_json);
			
			com.alibaba.fastjson.JSONObject o = com.alibaba.fastjson.JSONObject.parseObject(res_json);
			String token = o.getString("access_token");
			
			com.alibaba.fastjson.JSONObject  jsonObject  = new com.alibaba.fastjson.JSONObject ();
			jsonObject.put("touser", "o3PxO0aGXf8hOmYoE39MJTqWzAOk");
			jsonObject.put("template_id", "6MJ3yG-OYTsi8qxCYO8yAl7SmK_II0Q8V2QR7yDPDXc");
			
			com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
			com.alibaba.fastjson.JSONObject first = new com.alibaba.fastjson.JSONObject();
			first.put("value", "服务完成通知");
			first.put("color", "#173177");
			
			com.alibaba.fastjson.JSONObject keyword1 = new com.alibaba.fastjson.JSONObject();
	        keyword1.put("value", "项目已通过");
	        keyword1.put("color", "#173177");
	        
	        com.alibaba.fastjson.JSONObject keyword2 = new com.alibaba.fastjson.JSONObject();
	        keyword2.put("value", UtilDate.getTime(new Date()));
	        keyword2.put("color", "#173177");
	        
	        com.alibaba.fastjson.JSONObject remark = new com.alibaba.fastjson.JSONObject();
	        remark.put("value", "感谢您选择我们的服务");
	        remark.put("color", "#173177");
	        
	        data.put("first",first);
	        data.put("keynote1",keyword1);
	        data.put("keynote2",keyword2);
	        data.put("remark",remark);

	        jsonObject.put("data", data);
			
	        String post_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token ;
	        String res_info =  HTTPClientUtils.postRequest(post_url, jsonObject.toJSONString());
	        log.info(res_info);
	        
	        String ipAddress = RequestIp.getIPAddress(request);
	        log.info(ipAddress);//
	        
			return res_info;
		}catch (Throwable e) {
			e.printStackTrace();
			log.info("错误信息"+e.getMessage());
			return null;
		}
	}


	@Autowired
    WxPayService wxPayService;
	
	@RequestMapping(value = "userWithgraw", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String  userWithgraw(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response)  {
		try{
			//log.info("提现红包TEST");
			 
			//String appid="wx487b598049f3a162"   ;
			//String secret = "7afd7b083512837aad16295d2de49b22";
			
			EntPayService entPayService = wxPayService.getEntPayService();
			EntPayRequest req = new EntPayRequest();
			req.setPartnerTradeNo(UtilDate.getOrderNum()+UtilDate.getThree());
			req.setOpenid("o3PxO0azbuoeACZriC-bRAZDHrFM");
			req.setCheckName("NO_CHECK");
			req.setAmount(new BigDecimal(0.4).multiply(new BigDecimal("100")).intValue());
			req.setDescription("企业付款");
			String ipAddress = RequestIp.getIPAddress(request);
			req.setSpbillCreateIp(ipAddress);
			EntPayResult entPayResult =null;
			try{
		        entPayResult = entPayService.entPay(req);
		        log.info("返回消息：  错误码 "+ entPayResult.getErrCode() +"， 错误消息  "+ entPayResult.getErrCodeDes());
	
		        if (BeanUtil.isEmpty(entPayResult.getPaymentNo())) {
		            log.info(String.format("订单号： %s 企业付款失败")); 
		            //throw new GeneralException("081", "企业付款失败");
		        	return "付款失败";
		        }
			
			}catch(Exception e){
				log.info("付款错误返回信息："+e.getMessage());
				//log.info("返回错误码 "+ entPayResult.getErrCode() +" 错误消息  "+ entPayResult.getErrCodeDes());
				return "付款失败";
			}
	        
			return ipAddress;
		}catch (Throwable e) {
			e.printStackTrace();
			log.info("错误信息"+e.getMessage());
			return null;
		}
	}
	
	
	@RequestMapping(value = "wxOrderCallBack", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String wxOrderCallBack(HttpServletRequest req) throws Exception {
        String xmlResult = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
        log.info(String.format("订单回调参数：%s", xmlResult));
//        String s1 = orderService.wxOrderCallBack(xmlResult);
//        log.info(s1);
        String s1 =  WxPayNotifyResponse.success("处理成功!");
        
        return s1;
    }

}





